import React from "react";
import { connect } from "dva";
import { Button, Icon, Radio, Form, Input } from "antd";
import "./Images.less";
import Uploaddd from "./UploadImg";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

@connect(({ add }) => ({
  add: add
}))
class Images extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      radioValue: 1,
      index: 0,
      marginLeft: 0,
      marginRight: 0,
      imgList: [
        {
          key: 0,
          url: "",
          title: "",
          intro: ""
        }
      ],
      titleLength: 0,
      titleValue: "",
      keyLength: 0,
      introLength: 0,
      num: 0
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    window.PubSub.subscribe("imgAll", this.setImgAll);
  }
  componentWillUnmount() {
    this.props.dispatch({ type: "add/resetPushClick" });
  }
  onChangeRadio = e => {
    this.setState({
      radioValue: e.target.value
    });
    if (e.target.value == 1) {
      this.setFields({
        url: ""
      });
    }
  };
  /**
   * 获取title length
   */
  getTitleLength = e => {
    let length = e.target.value.length;
    if (length <= 60) {
      this.setState({
        titleLength: length,
        titleValue: e.target.value
      });
    }
    window.PubSub.publish("tabTitle", e.target.value);
  };
  /**
   * 增加列表
   */
  addImgList = () => {
    let imgArr = [...this.state.imgList];
    let index = this.state.num;
    imgArr.push({
      key: index + 1,
      url: "",
      title: "",
      intro: ""
    });
    this.setState({
      imgList: imgArr,
      num: index + 1
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });

    // console.log(index);
  };
  /**
   * 删除列表
   */
  deletImgList = index => {
    let imgArr = [...this.state.imgList];

    imgArr.forEach((item, indexs) => {
      if (item.key == index) {
        imgArr.splice(indexs, 1);
      }
    });
    this.setState({
      imgList: imgArr,
      num: this.state.num - 1
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  /**
   * 设置值
   */
  setListInput = (e, key) => {
    let imgArr = [...this.state.imgList];
    // eslint-disable-next-line array-callback-return
    imgArr.map((item) => {
      if (item.key === key) {
       item.title = e.target.value;
      }
    });
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  setListText = (e, key) => {
    let imgArr = [...this.state.imgList];
    imgArr.map((item, index) => {
      if (item.key === key) {
        item.intro = e.target.value;
      }
    });
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  setListUrl = (data, key) => {
    let imgArr = [...this.state.imgList];
    imgArr.map((item, index) => {
      if (item.key === key) {
        item.url = data;
      }
    });
    this.setState({
      imgList: imgArr
    });
    this.props.dispatch({ type: "add/setUploadImageList", data: imgArr });
  };
  /**
   * 关闭
   */
  close = key => {
    this.props.dispatch({
      type: "add/close",
      key: key
    });
  };
  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue();
    let about = [];
    this.props.add.gltjData.map((item, index) => {
      about.push(item.information_id);
    });
    data["about"] = about.join();
    data["img_arr"] = this.state.imgList;
    data["type"] = 2;
    return data;
  };
  getFieldsValue = () => {
    let data = this.props.form.getFieldsValue();
    this.props.form.validateFields();
    let validateArr = this.props.form.getFieldsError();
    let isDown = true;
    for (const key in validateArr) {
      if (validateArr.hasOwnProperty(key)) {
        //判断是否有效验错误
        if (validateArr[key]) {
          isDown = false;
          return;
        }
      }
    }
    if (isDown) {
      let about = [];
      this.props.add.gltjData.forEach((item, index) => {
        about.push(item.information_id);
      });
      data["about"] = about.join();
      data["img_arr"] = this.state.imgList;
      data["type"] = 2;
      return data;
    }
  };
  /**
   * 重置表单
   */
  resetFields = () => {
    this.props.form.resetFields();
    this.setState({
      titleValue: ""
    });
  };
  /**
   * 设置表单值
   */
  setFields = data => {
    // let fdata = this.props.form.getFieldsValue();
    // console.log(fdata);
    // console.log(data);
    let setData = {};
    setData.information_title = data.title;
    setData.intro = data.summary;
    setData.key_word = data.keyword;
    setData.content = data.content;
    setData.url = data.url;
    setData.img_arr = data.img_arr;
    // console.log(setData);
    this.props.form.setFieldsValue(setData);
    this.setState({
      titleValue: setData.information_title
    });
    if (setData.url) {
      this.setState({
        radioValue: 2
      });
    }
    if (setData.img_arr && setData.img_arr.length) {
      let arr = [];
      setData.img_arr.forEach((item, index) => {
        arr.push({
          key: index,
          url: item.url,
          title: item.title,
          intro: item.intro
        });
      });
      this.setState({
        imgList: arr,
        num: arr.length
      });
      this.props.dispatch({ type: "add/setUploadImageList", data: arr });
    }
    if (data.about) {
      this.props.dispatch({ type: "add/setPushClick", data: data.about_list });
    }
  };
  /**
   * 订阅
   */
  setImgAll = data => {
    if (data.type === "biz_sobey_picture") {
      let imgList = [...this.state.imgList];
      let length = imgList.length;
      let num = this.state.num;
      if (num < length) {
        imgList[num].url = data.keyFrameUrl;
        this.setState({
          num: num + 1,
          imgList: imgList
        });
        this.props.dispatch({ type: "add/setUploadImageList", data: imgList });
      } else {
        imgList[0].url = data.keyFrameUrl;
        this.setState({
          num: 1
        });
      }
    }
  };
  /**
   * 从内容库选择
   */
  getfromContent = () => {
    if (window.bar) {
      window.bar.show("picture", "ggsc"); //图片
      this.props.dispatch({ type: "add/saveMchType", data: "imgAll" });
    }
  };
  render() {
    const { getFieldDecorator } = this.props.form;
    const myValidateFields = (rule, values, callback) => {
      var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
      if (values) {
        if (!reg.test(values)) {
          callback("请输入正确的URL");
        }
      }
      callback();
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 }
      }
    };
    let gltjData = this.props.add.gltjData;
    if (!gltjData) {
      gltjData = [];
    }

    //将当前this传递给父类
    this.props.onRef(this);

    return (
      <div className="Images">
        <Form>
          <FormItem label="">
            <p className="title_show">
              <span className="required">*</span>
              {getFieldDecorator("information_title", {
                rules: [
                  {
                    required: true,
                    message: "请输入标题"
                  }
                ]
              })(<Input placeholder="请输入标题" className="artical_title" onChange={this.getTitleLength} size="large" style={{ width: "100%", paddingRight: "90px" }} maxLength={60} />)}
              <span className="rightInput">{this.state.titleLength}/60</span>
            </p>
          </FormItem>
          <FormItem {...formItemLayout} label="关键字">
            {getFieldDecorator("key_word")(
              <Input
                className="keyInput"
                onChange={e => {
                  let data = e.target.value;
                  if (data.length <= 50) {
                    this.setState({
                      keyLength: data.length
                    });
                  }
                }}
                maxLength={50}
              />
            )}
            <span className="showKeyLength">{this.state.keyLength}/50</span>
          </FormItem>
          <FormItem {...formItemLayout} label="摘要">
            {getFieldDecorator("intro")(
              <TextArea
                placeholder="请输入摘要"
                autosize={{ minRows: 2, maxRows: 6 }}
                className="introInput"
                onChange={e => {
                  let data = e.target.value;
                  if (data.length <= 200) {
                    this.setState({
                      introLength: data.length
                    });
                  }
                }}
                maxLength={200}
              />
            )}
            <span className="showTextLength">{this.state.introLength}/200</span>
          </FormItem>
          <RadioGroup onChange={this.onChangeRadio} value={this.state.radioValue} style={{ marginBottom: "10px" }}>
            <Radio value={1}>内容编辑模式</Radio>
            <Radio value={2}>URL模式</Radio>
          </RadioGroup>
          {this.props.add.configJson.mchSwitch ? (
            <Button style={this.state.radioValue === 2 ? { display: "none" } : {}} onClick={this.getfromContent}>
              从内容库选择
            </Button>
          ) : (
            ""
          )}
          <p style={this.state.radioValue === 2 ? { display: "none" } : {}}>注：请上传1-15张图片，上传图片推荐尺寸，推荐2M,图片格式为jpg/png</p>
          <FormItem label="">
            {getFieldDecorator("url", {
              rules: [
                {
                  validator: myValidateFields
                }
              ]
            })(<Input placeholder="请输入url链接" style={this.state.radioValue === 1 ? { display: "none" } : {}} />)}
          </FormItem>
        </Form>
        <div style={this.state.radioValue === 2 ? { display: "none" } : {}}>
          {this.state.imgList.map((item, index) => {
            return (
              <div className="imgList" key={index}>
                <div className="img_upload">
                  <Uploaddd setUrl={data => this.setListUrl(data, item.key)} img={item.url} />
                </div>
                <div className="imgList_right">
                  <div>
                    图片标题：
                    <Input style={{ width: "80%" }} value={item.title} onChange={e => this.setListInput(e, item.key)} />
                  </div>
                  <div className="imgList_text">
                    <span>图片描述：</span>
                    <TextArea placeholder="图片描述" style={{ width: "80%" }} value={item.intro} onChange={e => this.setListText(e, item.key)} autosize={{ minRows: 4, maxRows: 6 }} />
                  </div>
                  <span className="delet_imgList" onClick={() => this.deletImgList(item.key)}>
                    删除
                  </span>
                </div>
              </div>
            );
          })}
          <div className="add_imgList" onClick={this.addImgList}>
            <Icon type="plus" theme="outlined" />
          </div>
        </div>
      </div>
    );
  }
}

const ImagesFrom = Form.create()(Images);
export default ImagesFrom;
